package com.unlcn.ils.sales.backend.service;

import cn.huiyunche.commons.exception.BusinessException;
import cn.huiyunche.commons.utils.HttpRequestUtil;
import cn.huiyunche.commons.utils.QiniuUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.unlcn.ils.sales.backend.bo.BrandBO;
import com.unlcn.ils.sales.backend.bo.OrderSkuBO;
import com.unlcn.ils.sales.backend.constant.AutoConfConstant;
import com.unlcn.ils.sales.base.mapper.SaleOrderSkuMapper;
import com.unlcn.ils.sales.base.model.SaleOrderSku;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * Created by houjianhui on 2017/5/27.
 */
@Service
public class OrderSkuServiceImpl implements OrderSkuService {
    private static final Logger LOGGER = LoggerFactory.getLogger(OrderSkuServiceImpl.class);

    @Autowired
    private SaleOrderSkuMapper orderSkuMapper;

    @Autowired
    private AutoConfConstant autoConfConstant;

    @Override
    public Integer save(String bo, Integer saleOrderId) throws Exception {
        LOGGER.info("OrderSkuServiceImpl.save params OrderSkuBO: {}", bo);

        if (StringUtils.isBlank(bo)) {
            LOGGER.info("OrderSkuServiceImpl.save params OrderSkuBO is null");
            throw new IllegalArgumentException("销售订单商品车信息不能为空");
        } else if (Objects.equals(saleOrderId, null) || Objects.equals(saleOrderId, "")) {
            LOGGER.info("OrderSkuServiceImpl.save params saleOrderId is null");
            throw new IllegalArgumentException("销售订单ID不能为空");
        }

        List<OrderSkuBO> skuBOS = JSONArray.parseArray(bo, OrderSkuBO.class);

        if (CollectionUtils.isEmpty(skuBOS)) {
            LOGGER.info("OrderSkuServiceImpl.save params OrderSkuBO must be not null");
            throw new IllegalArgumentException("销售订单商品车信息不能为空");
        }

        skuBOS.stream().forEach(val -> {
            val.setSaleOrderId(saleOrderId);
            if (val.getVinList() !=null && val.getVinList().size()>0) {
                val.getVinList().stream().forEach(str -> {
                    // 保存数据
                    SaleOrderSku sku = new SaleOrderSku();
                    BeanUtils.copyProperties(val, sku);
                    sku.setVin(str);
                    sku.setAmt(1);
                    try {
                        orderSkuMapper.insertSelective(sku);
                    } catch (Exception e) {
                        LOGGER.error("OrderSkuServiceImpl.save error: {}", e);
                        throw new BusinessException("保存销售订单商品车信息异常");
                    }
                });
            } else {
                for (int i=0;i<val.getAmt();i++) {
                    SaleOrderSku sku = new SaleOrderSku();
                    BeanUtils.copyProperties(val, sku);
                    sku.setAmt(1);
                    sku.setVin("");
                    try {
                        orderSkuMapper.insertSelective(sku);
                    } catch (Exception e) {
                        LOGGER.error("OrderSkuServiceImpl.save error: {}", e);
                        throw new BusinessException("保存销售订单商品车信息异常");
                    }
                }
            }
        });

        return null;
    }

    @Override
    public List<BrandBO> listBrand(String cvKeyword) throws Exception {
        LOGGER.info("OrderSkuServiceImpl.listBrand param cvkeyword: {}", cvKeyword);
        if (StringUtils.isBlank(cvKeyword)) {
            return null;
        }
        List<BrandBO> brandBOs = resolvBrandFormSCResult(cvKeyword);
        if (CollectionUtils.isNotEmpty(brandBOs)) {
            brandBOs.stream().forEach(val -> {
                val.setBrandLogoUrl(QiniuUtil.generateDownloadURL("brand-logo", val.getBrandLogoUrl(), "", null, null));
            });
        }
        return brandBOs;
    }

    private List<BrandBO> resolvBrandFormSCResult(String key) throws Exception {
//        String url = autoConfConstant.getSc() + "/api/model/base/cv/queryModel/" + key;
        String url = autoConfConstant.getOperation() + "/api/brandSeries/queryBrands/" + key;
//        Integer time = autoConfConstant.getScTime();
        Integer time = autoConfConstant.getOperationTime();
        String result = HttpRequestUtil.sendHttpGet(url, null, time);
        if (!Objects.equals(result, null)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            String msgCode = jsonObject.getString("messageCode");
            String msg = jsonObject.getString("message");
            String data = jsonObject.getString("data");
            Boolean success = jsonObject.getBoolean("success");
            List<BrandBO> bos = JSONArray.parseArray(data, BrandBO.class);
            if (!success) {
                LOGGER.info("OrderSkuServiceImpl resolvBrandFormSCResult result error");
                throw new BusinessException(msgCode, msg);
            }
            return bos;
        }
        return null;
    }
}
